<?php
declare(strict_types=1);

namespace lib;

use JsonSerializable;
use Serializable;
use mexti\MinHeapNode;
use stdClass;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
use sys\Log;

class User extends \lib\sync\SyncableData {
    use data\traits\MidTrait;

    protected static string $SyncKey = 'User';
    protected static string $TableName = 'tp_nb_user';

    public int    $id;
    public int    $mid;
    public int    $role_id;
    public string $token;

    public string $username;
    public string $mickname;
    public ?string $tel;
    public int    $active;
    public array  $roles;

    public ?\lib\Merchant $merchant;

    protected static array $propNamesC = ['id', 'mid', 'role_id', 'username', 'realname', 'tel', 'roles'];
    protected static array $propNamesU = ['id', 'mid', 'role_id', 'username', 'realname', 'tel', 'roles'];
    protected static array $propNamesJ = ['id', 'mid', 'role_id', 'username', 'realname', 'tel', 'roles'];

    public function __construct(array $data) {
        parent::__construct($data);
        $this->traitInit();
        $this->merchant = \lib\Merchant::get($this->mid);
    }

    static protected function buildSyncSelect(\sys\Db $db, int $mid, int $time, int $lastId = 0) :\sys\SqlBuilder {
    
        $sql = $db->table('el_user_role,tp_user')
            ->join('tp_user','tp_user.id=el_user_role.uid')
            ->field([
                'tp_user.id',
                'tp_user.username',
                'el_user_role.mid AS mid',
                'COALESCE(el_user_role.szDisplayName, tp_user.realname, tp_user.username) as realname',
                'COALESCE(el_user_role.szTel, \'\') AS tel',
                'el_user_role.role_id',
                'el_user_role.roles',
            ])->order('tp_user.id ASC');
        if(0 == $lastId){
            return $sql->where([
                ['el_user_role.mid', '=', $mid],
            ]);
        }
        return $sql->where([
            ['el_user_role.mid', '=', $mid],
            ['tp_user.id', '>', $lastId],
        ]);
    }
}